package com.yuexia.yxim.client.handler;

import com.yuexia.yxim.client.client.ClientSession;
import com.yuexia.yxim.common.bean.msg.ProtoMsg;
import com.yuexia.yxim.common.enums.ProtoInstant;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Author: yue_xia
 * @Date: 2020/6/1 11:09 下午
 */
@Service
@Slf4j
@ChannelHandler.Sharable
public class LoginResponceHandler extends ChannelInboundHandlerAdapter {

    /**
     * 有消息传过来
     * 主要业务逻辑处理
     *
     * 如果消息类型是请求响应并且是登录成功状态，则取出绑定的会话，再设置登录成功的状态
     * 如果不是请求响应则调用父类默认的入站处理方法，将数据包交给流水线的下一站handler业务处理器处理
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断类型
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType pkgType = pkg.getType();
        if (!pkgType.equals(ProtoMsg.HeadType.LOGIN_RESPONSE)) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断是否返回成功
        ProtoMsg.LoginResponse loginResponse = pkg.getLoginResponse();
        ProtoInstant.ResultCodeEnum result =
                ProtoInstant.ResultCodeEnum.values()[loginResponse.getCode()];

        if (!result.equals(ProtoInstant.ResultCodeEnum.SUCCESS)) {
            //登录失败
            log.info("登录失败: {}", result.getDesc());
        }else {
            ClientSession.loginSuccess(ctx, pkg);

            ChannelPipeline pipeline = ctx.pipeline();
            //移除登录响应处理器
            pipeline.remove(this);
            //动态加入心跳处理器
            pipeline.addAfter("encoder", "heartbeat", new HeartBeatClientHandler());
        }


    }
}
